import mqtt from "mqtt";

class MqttClient {
    constructor() {
        this.client = null;
    }

    // 连接 MQTT Broker
    connect(brokerUrl, options) {
        this.client = mqtt.connect(brokerUrl,options );
            console.log(options)
        this.client.on("connect", () => {
            console.log("Connected to MQTT Broker");
        });

        this.client.on("error", (error) => {
            console.error("MQTT Error:", error);
            if (error.message.includes("Not authorized")) {
                // JWT 过期或无效，重新获取并连接
                this.reconnect();
            }
        });
    }


    // 重新连接
    async reconnect() {
        if (this.client) {
            this.client.end(); // 断开当前连接
        }
        //await this.connect("ws://broker.emqx.io:8083/mqtt"); // 重新连接
    }

    // 订阅 Topic
    subscribe(topic, callback) {
        if (this.client && this.client.connected) {
            this.client.subscribe(topic, (err) => {
                if (!err) {
                    console.log(`Subscribed to topic: ${topic}`);
                    this.client.on("message", (receivedTopic, message) => {
                        if (receivedTopic === topic) {
                            callback(message.toString());
                        }
                    });
                } else {
                    console.error("Subscription failed:", err);
                }
            });
        } else {
            console.error("MQTT client is not connected");
        }
    }

    // 发布消息
    publish(topic, message) {
        if (this.client && this.client.connected) {
            this.client.publish(topic, message, (err) => {
                if (!err) {
                    console.log(`Published message to topic: ${topic}`);
                } else {
                    console.error("Publish failed:", err);
                }
            });
        } else {
            console.error("MQTT client is not connected");
        }
    }

    // 取消订阅
    unsubscribe(topic) {
        if (this.client && this.client.connected) {
            this.client.unsubscribe(topic, (err) => {
                if (!err) {
                    console.log(`Unsubscribed from topic: ${topic}`);
                } else {
                    console.error("Unsubscribe failed:", err);
                }
            });
        } else {
            console.error("MQTT client is not connected");
        }
    }

    // 断开连接
    disconnect() {
        if (this.client) {
            this.client.end();
            console.log("Disconnected from MQTT Broker");
        }
    }
}

export default new MqttClient();
